<!-- 物料分类 -->
<template>
 <view style="height: 100vh;">
  <layout index="/pages/wms/index" layoutTitle="物料分类">
  <view class="container">
    <!-- 顶部导航 -->


    <!-- 搜索栏 -->
    <view class="search-box">
      <van-field
        v-model="queryParams.code"
        placeholder="输入分类编码"
        clearable
        border
        @confirm="handleQuery"
      >
        <template #button>
          <van-button 
            size="small" 
            type="primary" 
            color="#07c160"
            @click="handleQuery"
          >
            搜索
          </van-button>
        </template>
      </van-field>
    </view>

    <!-- 分类树形列表 -->
    <scroll-view scroll-y class="category-list">
      <view v-for="item in processedList" :key="item.id">
        <view 
          class="category-item" 
          :style="{paddingLeft: `${20 + item.level * 30}rpx`}"
        >
          <view class="item-main" @click="toggleExpand(item)">
            <view class="item-info">
              <text class="item-name">{{ item.name }}</text>
              <text class="item-code">{{ item.code }}</text>
            </view>
            <view class="item-actions">
              <van-icon
                v-if="item.children?.length"
                :name="item.expanded ? 'arrow-down' : 'arrow'"
                color="#999"
                size="36rpx"
              />
            </view>
          </view>
          
          <view class="item-controls">
            <van-icon name="plus" color="#07c160" @click.stop="handleAddChild(item)"/>
            <van-icon name="edit" color="#07c160" @click.stop="handleEdit(item)"/>
            <van-icon name="delete" color="#07c160" @click.stop="handleDelete(item)"/>
          </view>
        </view>

        <!-- 子分类 -->
        <view 
          v-if="item.expanded && item.children?.length"
          class="children-list"
        >
          <view 
            v-for="child in item.children"
            :key="child.id"
            class="category-item"
            :style="{paddingLeft: `${20 + child.level * 30}rpx`}"
          >
            <!-- 子项内容同理 -->
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 编辑弹窗 -->
    <van-popup
      :show="showForm"
      position="bottom"
      round
      closeable
      @close="closeForm"
      custom-style="height: 65%"
    >
      <van-form @submit="submitForm">
        <view class="form-header">{{ formTitle }}</view>
        
        <van-field
          readonly
          clickable
          name="parent"
          label="父级分类"
          :value="selectedParentName"
          placeholder="点击选择"
          @click="showTreePicker = true"
        />
        
        <van-field
          v-model="formData.code"
          label="分类编码"
          placeholder="请输入编码"
          :rules="[{ required: true, message: '编码不能为空' }]"
        />
        
        <van-field
          v-model="formData.name"
          label="分类名称"
          placeholder="请输入名称"
          :rules="[{ required: true, message: '名称不能为空' }]"
        />
        
        <van-field
          v-model="formData.remark"
          label="说明"
          type="textarea"
          autosize
          placeholder="请输入说明"
        />
        
        <view class="form-submit">
          <van-button 
            round 
            block 
            type="primary" 
            color="#07c160"
            native-type="submit"
          >
            确认提交
          </van-button>
        </view>
      </van-form>
    </van-popup>

    <!-- 父级选择器 -->
    <van-popup
      :show="showTreePicker"
      position="bottom"
      round
      custom-style="height: 50%"
    >
      <van-tree-select
        :items="treeOptions"
        :main-active-index="activeTreeIndex"
        @click-nav="handleTreeNav"
      >
        <template #content>
          <scroll-view scroll-y class="tree-content">
            <view
              v-for="item in treeChildren"
              :key="item.id"
              class="tree-item"
              @click="selectParent(item)"
            >
              {{ item.name }}
              <text class="tree-item-code">{{ item.code }}</text>
            </view>
          </scroll-view>
        </template>
      </van-tree-select>
    </van-popup>
  </view>
 </layout>
 </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';

// 模拟数据
const mockData = ref([
  {
    id: 1,
    code: '001',
    name: '原材料',
    parentId: null,
    remark: '基础原材料',
    children: [
      {
        id: 3,
        code: '001-01',
        name: '金属材料',
        parentId: 1,
        remark: '金属原材料'
      }
    ]
  },
  {
    id: 2,
    code: '002',
    name: '设备类',
    parentId: null,
    remark: '生产设备'
  }
]);

// 状态管理
const queryParams = reactive({ code: '' });
const formData = reactive({
  id: null,
  code: '',
  name: '',
  remark: '',
  parentId: null
});
const expandedItems = ref(new Set());
const showForm = ref(false);
const showTreePicker = ref(false);
const activeTreeIndex = ref(0);
const treeOptions = ref([]);
const treeChildren = ref([]);
const formTitle = ref('新增分类');

// 计算属性
const processedList = computed(() => {
  return processTreeData(mockData.value);
});

const selectedParentName = computed(() => {
  if (!formData.parentId) return '无父级';
  const parent = findItem(mockData.value, formData.parentId);
  return parent ? parent.name : '未知父级';
});

// 核心方法
const processTreeData = (data, parentId = null, level = 0) => {
  return data
    .filter(item => item.parentId === parentId)
    .map(item => ({
      ...item,
      level,
      expanded: expandedItems.value.has(item.id),
      children: processTreeData(data, item.id, level + 1)
    }));
};
	
const toggleExpand = (item) => {
  const method = item.expanded ? 'delete' : 'add';
  expandedItems.value[method](item.id);
};

const handleAdd = (parent = null) => {
  resetForm();
  formData.parentId = parent?.id || null;
  formTitle.value = '新增分类';
  showForm.value = true;
};

const handleEdit = (item) => {
  Object.assign(formData, item);
  formTitle.value = '编辑分类';
  showForm.value = true;
};

const handleDelete = async (item) => {
  uni.showModal({
    title: '删除确认',
    content: `确定删除 ${item.name} 分类吗？`,
    success: async ({ confirm }) => {
      if (confirm) {
        await deleteItem(item.id);
        uni.showToast({ title: '删除成功', icon: 'success' });
      }
    }
  });
};

// 数据操作
const findItem = (items, id) => {
  for (const item of items) {
    if (item.id === id) return item;
    if (item.children) {
      const found = findItem(item.children, id);
      if (found) return found;
    }
  }
  return null;
};

const deleteItem = (id) => {
  const removeFromParent = (items) => {
    return items.filter(item => {
      if (item.id === id) return false;
      if (item.children) {
        item.children = removeFromParent(item.children);
      }
      return true;
    });
  };
  mockData.value = removeFromParent(mockData.value);
};

const submitForm = async () => {
  if (formData.id) {
    await updateItem(formData);
  } else {
    await addItem(formData);
  }
  closeForm();
  uni.showToast({ title: '操作成功', icon: 'success' });
};

const addItem = (data) => {
  const newItem = {
    ...data,
    id: Date.now(),
    children: []
  };
  
  if (data.parentId) {
    const parent = findItem(mockData.value, data.parentId);
    parent?.children.push(newItem);
  } else {
    mockData.value.push(newItem);
  }
};

const updateItem = (data) => {
  const item = findItem(mockData.value, data.id);
  if (item) {
    Object.assign(item, data);
  }
};

// 辅助方法
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    code: '',
    name: '',
    remark: '',
    parentId: null
  });
};

const closeForm = () => {
  showForm.value = false;
  showTreePicker.value = false;
  resetForm();
};

// 初始化
onMounted(() => {
  treeOptions.value = mockData.value
    .filter(item => !item.parentId)
    .map(item => ({ text: item.name }));
});
</script>

<style>
.container {
  padding: 20rpx;
  background: linear-gradient(165deg, #f6fbf8, #e8f5f0);
  min-height: 100vh;
}

/* 搜索框样式 */
.search-box {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 16rpx;
  margin-bottom: 24rpx;
  box-shadow: 0 4rpx 12rpx rgba(39, 174, 96, 0.1);
}

:deep(.van-field__body) {
  background-color: #f6fbf8;
  border-radius: 8rpx;
  padding: 0 12rpx;
}

:deep(.van-button--primary) {
  background-color: #27ae60 !important;
  border-color: #27ae60 !important;
  transition: all 0.3s ease;
}

:deep(.van-button--primary:active) {
  background-color: #219654 !important;
  border-color: #219654 !important;
}

/* 分类列表样式 */
.category-list {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 16rpx 0;
  margin-bottom: 24rpx;
  max-height: calc(100vh - 240rpx);
  box-shadow: 0 4rpx 12rpx rgba(39, 174, 96, 0.1);
}

.category-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24rpx 20rpx;
  border-bottom: 1px solid rgba(39, 174, 96, 0.1);
  transition: all 0.3s ease;
}

.category-item:last-child {
  border-bottom: none;
}

.category-item:active {
  background-color: rgba(39, 174, 96, 0.05);
}

.item-main {
  display: flex;
  flex: 1;
  justify-content: space-between;
  align-items: center;
}

.item-info {
  display: flex;
  flex-direction: column;
}

.item-name {
  font-size: 32rpx;
  color: #2c3e50;
  font-weight: 600;
  margin-bottom: 6rpx;
}

.item-code {
  font-size: 24rpx;
  color: #7f8c8d;
}

.item-actions {
  margin-left: 20rpx;
}

.item-controls {
  display: flex;
  gap: 24rpx;
}

:deep(.van-icon) {
  font-size: 36rpx;
  color: #27ae60 !important;
  padding: 8rpx;
  border-radius: 50%;
  background-color: rgba(39, 174, 96, 0.1);
  transition: all 0.3s ease;
}

:deep(.van-icon:active) {
  background-color: rgba(39, 174, 96, 0.2);
  transform: scale(0.95);
}

/* 子分类列表 */
.children-list {
  background-color: rgba(39, 174, 96, 0.03);
  border-left: 4rpx solid #27ae60;
  margin-left: 40rpx;
}

/* 表单样式 */
.form-header {
  font-size: 36rpx;
  font-weight: bold;
  color: #2c3e50;
  text-align: center;
  padding: 30rpx 0;
  position: relative;
}

.form-header::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 60rpx;
  height: 4rpx;
  background-color: #27ae60;
  border-radius: 2rpx;
}

:deep(.van-cell) {
  padding: 24rpx 32rpx !important;
}

:deep(.van-field__label) {
  color: #2c3e50 !important;
  font-weight: 500;
}

.form-submit {
  padding: 40rpx 32rpx;
}

:deep(.van-button--round) {
  border-radius: 50rpx !important;
  height: 90rpx !important;
  font-size: 32rpx !important;
  font-weight: 500 !important;
  box-shadow: 0 6rpx 12rpx rgba(39, 174, 96, 0.2);
}

/* 树形选择器 */
.tree-content {
  height: 60vh;
  padding: 20rpx 30rpx;
}

.tree-item {
  padding: 24rpx 0;
  border-bottom: 1px solid rgba(39, 174, 96, 0.1);
  color: #2c3e50;
  font-size: 28rpx;
}

.tree-item-code {
  margin-left: 12rpx;
  font-size: 24rpx;
  color: #7f8c8d;
}

/* 动画效果 */
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.category-item {
  animation: fadeIn 0.3s ease-out forwards;
}

.category-item:nth-child(1) { animation-delay: 0.05s; }
.category-item:nth-child(2) { animation-delay: 0.1s; }
.category-item:nth-child(3) { animation-delay: 0.15s; }
.category-item:nth-child(4) { animation-delay: 0.2s; }
.category-item:nth-child(5) { animation-delay: 0.25s; }
.category-item:nth-child(6) { animation-delay: 0.3s; }
.category-item:nth-child(7) { animation-delay: 0.35s; }
.category-item:nth-child(8) { animation-delay: 0.4s; }
.category-item:nth-child(9) { animation-delay: 0.45s; }
.category-item:nth-child(10) { animation-delay: 0.5s; }
</style>